package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.Conver_MD5;
import com.nikmesoft.android.referendumfriend.models.user_login;
import com.nikmesoft.android.referendumfriend.service.ImageDownloader;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class Login extends BaseActivity {
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		LoginHandler.result=null;
		finish();
	}


	private EditText edu, edp;
	private ProgressDialog dialog;
	private WSLoader loader;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		if (LoginHandler.result==null) LoginHandler.result=new user_login();
		init();
	}

	private void init() {
		edu = (EditText) findViewById(R.id.login_eduser);
		edp = (EditText) findViewById(R.id.login_edpass);
		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
		
	}

	public void Register_activity(View v) {
		Intent intent = new Intent(this, Login_register.class);
		startActivity(intent);
	}

	public void Forgot_activity(View v) {
		Intent intent = new Intent(this, Login_forgot.class);
		startActivity(intent);
	}

	public void home_ativity(View v) {
		if(edp.getText().toString().equals("")||edu.getText().toString().equals("")) 
		{
			toad("Not be blank!");
			return;
		}
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			LoginHandler.result.setPass(edp.getText().toString().trim());
			String pass=Conver_MD5.md5Digest(edp.getText().toString().trim());
			loader.execute(edu.getText().toString().trim(),pass);
		}
		

		
	}
	public void home_activities()
	{
		
		Intent intent = new Intent(this, Home.class);
		startActivity(intent);
	}

	private String callWS(String name1, String name2) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<login soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<LoginRequest xsi:type=\"rdf:LoginRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<username xsi:type=\"xsd:string\">"
				+ name1
				+ "</username>"
				+ "<password xsi:type=\"xsd:string\">"
				+ name2
				+ "</password>"
				+ "</LoginRequest>"
				+ "</login>"
				+ "</soapenv:Body>"
				+ "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private user_login xmlParser(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			LoginHandler handler = new LoginHandler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private class WSLoader extends AsyncTask<String, Integer, user_login> {

		@Override
		protected user_login doInBackground(String... params) {
			user_login us=xmlParser(callWS(params[0], params[1]));
			
			try {
				Bitmap bm=null;
				bm=ImageDownloader.downloadImage(LoginHandler.result.getAvatar());
				LoginHandler.result.setBit(bm);
			}catch(Exception ex)
			{
				
			}
			
			return us;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(user_login result) {
		
			super.onPostExecute(result);
			try {
			if (result.getError()!= null) toad(result.getError().getErrorMsg());
			else 
			{
				home_activities();
				
			}
			dialog.dismiss();
			}
			catch(Exception ex)
			{
				dialog.dismiss();
				toad("No Internet Connection!");
			}
	
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}

	
	public void toad(String str){
		CommonUtil.toastNotify(this,str);
	}
}